<!--上传批次-->
<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formData" class="user-search">
      <el-form-item label="上传批次">
        <el-input clearable size="small" v-model="formData.name" placeholder="输入上传批次"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
      <el-table-column align="center" sortable prop="name" label="批次名称">
      </el-table-column>
      <el-table-column align="center" sortable prop="desc" label="备注">
      </el-table-column>
      <el-table-column align="center" sortable prop="createAt" label="创建时间" width="180">
        <template slot-scope="scope">
          <div>{{scope.row.createAt | timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template slot-scope="scope">
          <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
          <el-button size="mini" type="primary" @click="toDataList(scope.$index, scope.row)">查看数据</el-button>
          <el-button size="mini" type="danger" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 添加/编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="40%" @click="closeDialog">
      <el-form label-width="90px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="批次名称" prop="name">
          <el-input size="small" v-model="editForm.name" placeholder="请输入批次名称"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input size="small" type="textarea" :rows="2" v-model="editForm.desc" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="上传Excel" prop="fileList">
          <el-upload
            class="upload-demo"
            ref="upload"
            accept=".xlsx,.xls"
            :limit="1"
            action="#"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :file-list="editForm.fileList"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" v-loading.fullscreen.lock="fullscreenLoading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as XLSX from 'xlsx'
  import { getBatchList, saveBatch, delBatch } from '@/api/userMG';
  import Pagination from '@/components/Pagination';
  import { timestampToDate } from '@/utils/util';


  export default {
    data() {
      return {
        // nshow: true, //switch开启
        // fshow: false, //switch关闭
        loading: false, //表格是否显示加载
        fullscreenLoading: false,
        editFormVisible: false, //控制编辑页面显示与隐藏
        title: '添加',
        editForm: {
          editId: '',
          name: '',
          desc: '',
          fileList: []
        },
        // rules表单验证
        rules: {
          name: [{ required: true, message: '请输入批次名称', trigger: ['blur','change']}],
          // desc: [{ required: true, message: '请输入备注', trigger: ['blur','change'] }],
          fileList: [{ required: true, message: '请上传excel文件', trigger: ['blur','change'] }],
        },
        formData: {
          page: 1,
          limit: 10,
          name: '',
        },
        // 删除
        seletedata: {
          ids: '',
        },
        listData: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
      }
    },
    // 注册组件
    components: {
      Pagination
    },
    async created() {
      await this.getdata(this.formData)
    },
    methods: {
      // 获取任务列表
      async getdata() {
        this.loading = true
        await getBatchList(this.formData)
          .then(res => {
            this.loading = false
            if (res.data.success == false) {
              this.$message({
                type: 'info',
                message: res.data.msg
              })
            } else {
              this.listData = res.data.datas.data;
              // 分页赋值
              this.pageparm.currentPage = this.formData.page;
              this.pageparm.pageSize = this.formData.limit;
              this.pageparm.total = res.data.datas.count;
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err)
          })
      },
      // 分页插件事件
      callFather(parm) {
        this.formData.page = parm.currentPage
        this.formData.limit = parm.pageSize
        this.getdata(this.formData)
      },
      // 搜索事件
      search() {
        this.getdata()
      },
      // 显示编辑、增加弹出框
      handleEdit(index, row) {
        this.editFormVisible = true
        if (row != undefined && row != 'undefined') {
          this.title = '修改'
          this.editForm.editId = row.id
          this.editForm.name = row.name
          this.editForm.desc = row.desc
        } else {
          this.title = '添加'
          this.editForm.editId = ''
          this.editForm.name = new Date().getTime()+'（'+timestampToDate(new Date())+'）'
          this.editForm.desc = ''
          this.editForm.fileList = []
          this.editForm.xlsxData = []
        }
      },
      // 关闭编辑、增加弹出框
      closeDialog() {
        this.editFormVisible = false
      },
      // 编辑、增加页面保存方法
      submitForm(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            this.fullscreenLoading = true;
            saveBatch(this.editForm)
              .then(res => {
                this.editFormVisible = false
                this.fullscreenLoading = false
                if (res.data.success) {
                  this.getdata(this.formData)
                  this.$message({
                    type: 'success',
                    message: '操作成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.data.msg
                  })
                }
              })
              .catch(err => {
                this.editFormVisible = false
                this.fullscreenLoading = false
                this.$message.error(err)
              })
          } else {
            return false
          }
        })
      },
      // 删除
      handleDel(index, row) {
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delBatch({id:row.id})
              .then(res => {
                if (res.data.success) {
                  this.$message({
                    type: 'success',
                    message: '已删除!'
                  })
                  this.getdata(this.formData)
                } else {
                  this.$message({
                    type: 'info',
                    message: res.data.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error('删除失败！'+err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },

      // 删除文件时触发
      handleRemove() {
        this.editForm.fileList = []
        this.editForm.xlsxData = []
        this.$refs.editForm.validateField('fileList')
      },
      // 文件数量超过限定数量时触发
      handleExceed() {
        this.$message({
          type: 'warning',
          message: '一次最多上传一个文件'
        })
      },
      // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
      handleChange(param){
        console.log(66666,param);
        this.editForm.file = param.raw // .raw才是真实文件,给form表单
        const reader = new FileReader()
        reader.readAsBinaryString(param.raw) // 以二进制的方式读取
        reader.onload = (e) => {
          const fileString = e.target.result // 读取文件内容
          // 对文件内容进行处理
          const workbook = XLSX.read(fileString, { type: 'binary' }) // 解析二进制格式数据
          const worksheet = workbook.Sheets[workbook.SheetNames[0]] // 获取第一个Sheet
          const result = XLSX.utils.sheet_to_json(worksheet) // json数据格式
          console.log('最终数据格式', result) // 控制台打印数据
          // 对数据进行处理……
          // this.editForm.xlsxData = result
          this.$set(this.editForm, 'xlsxData', result)
          this.$set(this.editForm, 'fileList', [param])
          this.$refs.editForm.validateField('fileList')
        }
      },

      // 页面跳转
      toDataList(index,row){
        this.$router.push({path:'/index/dataList?batchid='+row.id+'&batchname='+row.name})
      },


    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }
</style>


